package com.zx.mes.hyl.scanner;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 注解扫描测试<br/>
 * https://www.cnblogs.com/hoonick/p/9820674.html<br/>
 * 寻找文件的地址没有错, todo:不过仍然报错java.nio.file.AccessDeniedException,检查了权限是有的,不知原因
 *
 * @author 华云龙
 * @date 2019-1-17
 */
public class AnnotationScannerTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Set<BeanDefinition> candidates = new LinkedHashSet<>();

        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        /// 指定扫描的位置
        Resource[] resources = resourcePatternResolver.getResources("classpath:com\\zx\\mes\\hyl\\*");

        MetadataReaderFactory metadata = new SimpleMetadataReaderFactory();

        for (Resource resource : resources) {
            System.out.println("resource:" + resource);
            MetadataReader metadataReader = metadata.getMetadataReader(resource);
            ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
            sbd.setResource(resource);
            sbd.setSource(resource);
            candidates.add(sbd);
        }

        for (BeanDefinition beanDefinition : candidates) {
            String className = beanDefinition.getBeanClassName();
            /// 扫描controller注解
            Controller controller = Class.forName(className).getAnnotation(Controller.class);

            if (controller != null) {
                System.out.println(className + ":" + controller);
            }
        }
    }
}
